package com.itheima.interceptor;

import com.itheima.util.CurrentHolder;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果没有请求头：拦截不放行，设置响应状态码401
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.warn("未登录，不允许访问");
            response.setStatus(401);
            return false;
        }
        //如果令牌非法：拦截不放行，设置响应状态码401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer i = claims.get("id", Integer.class);
            //线程添加id
            CurrentHolder.setCurrentId(i);
        } catch (Exception e) {
            log.warn("令牌非法，不允许访问");
            response.setStatus(401);
            e.printStackTrace();
            return false;
        }
        //放行
        return true;
    }
}
